# -*- coding: utf-8 -*-

import wx 

import model
import adapter

class WatchConfigDialog(wx.Dialog):
    def __init__(self, parent, id, title,  
                       size = (600, 400),
                       pos = wx.DefaultPosition,
                       style = wx.DEFAULT_DIALOG_STYLE, useMetal = False,
                       cfg = None):
        pre = wx.PreDialog()
        pre.Create(parent, id, title, pos, size, style)
        self.PostCreate(pre)
        self.config = cfg
        self.adapters = self.GetAdapters()
        self.CreateSizer()
        if self.config:
            self.InitContent()
        self.updateControlState()
                             
    def dataButtons(self):
        return ((wx.ID_OK, u'确定'),(wx.ID_CANCEL, u'取消'))
        
    def CreateSizer(self):
        sizer = wx.BoxSizer(wx.VERTICAL)
        self.CreateNameEntry(sizer)
        self.adapterConfigArea = self.CreateAdapterConfigArea(sizer)
        self.watchModeConfigArea = self.CreateWatchModeConfigArea(sizer)
        self.matchArgsConfigArea = self.CreateArgsConfigArea(sizer)
        #buttons
        btnsizer = wx.StdDialogButtonSizer()
        for eachId, eachLabel in self.dataButtons():
            self.CreateButton(btnsizer, eachId, eachLabel)
        btnsizer.Realize()
        sizer.Add(btnsizer, 0, wx.ALIGN_CENTER_HORIZONTAL | wx.ALL, 10)
        self.SetSizer(sizer)
        sizer.Fit(self)
        return sizer

    def CreateNameEntry(self,sizer):
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(self, -1, u'配置名称：'),0,wx.ALIGN_CENTER|wx.ALL, 5)
        self.nameField = wx.TextCtrl(self, -1, "", size = (250, -1))
        box.Add(self.nameField, wx.ALIGN_CENTER|wx.ALL, 5)
        sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        return box
    
    def CreateAdapterConfigArea(self,parentsizer):
        group = wx.StaticBox(self, -1, u'监听网站配置')
        sizer = wx.StaticBoxSizer(group,wx.VERTICAL)
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(self, -1, u'监听网站：'),0,wx.ALIGN_LEFT|wx.ALL, 5)
        self.adapterList = wx.Choice(self, -1,choices=[l.getName() for l in self.adapters])
        self.adapterList.SetSelection(0)
        box.Add(self.adapterList, wx.ALIGN_CENTER|wx.ALL, 5)
        sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(self, -1, u'版面名称：'),0,wx.ALIGN_LEFT|wx.ALL, 5)
        self.boardName =wx.TextCtrl(self, -1, u'SecondMarket', size = (250, -1))
        box.Add(self.boardName, wx.ALIGN_CENTER|wx.ALL, 5)
        sizer.Add(box, 0, wx.GROW|wx.ALL, 5)
        sizer.Layout()
        parentsizer.Add(sizer, 0, wx.EXPAND|wx.ALL, 5)
        return None

    
    def CreateWatchModeConfigArea(self, parentsizer):
        group = wx.StaticBox(self, -1, u'监听模式配置')
        sizer = wx.StaticBoxSizer(group,wx.VERTICAL)
        # keyword config
        panel = wx.Panel(self, -1)
        panelsizer = wx.GridSizer(rows=2, cols=2, hgap=10, vgap=10)
        self.matchModeRadios =[]
        for name in (u'所有新主题贴',u'所有新帖',u'符合条件的新主题贴',u'符合条件的新帖'):
            radiobutton = wx.RadioButton(panel, -1,name)
            panelsizer.Add(radiobutton)
            self.matchModeRadios.append(radiobutton)
            self.Bind(wx.EVT_RADIOBUTTON, self.OnMatchModeChanged, radiobutton)
        self.matchModeRadios[0].SetValue(True)
        panel.SetSizer(panelsizer)
        sizer.Add(panel, 1, wx.EXPAND|wx.ALL, 10)
        panelsizer.Layout()
        radioList = (u'所有新主题贴',u'所有新帖',u'符合条件的新主题贴',u'符合条件的新帖')
        sizer.Layout()
        parentsizer.Add(sizer, 1, wx.EXPAND|wx.ALL, 5)
        return panel
    
    def CreateArgsConfigArea(self,parentsizer):
        group = wx.StaticBox(self, -1, u'匹配参数配置')
        groupsizer = wx.StaticBoxSizer(group,wx.VERTICAL)
        panel = wx.Panel(self, -1)
        sizer = wx.BoxSizer(wx.VERTICAL)
        # keyword config
        box = wx.BoxSizer(wx.HORIZONTAL)
        box.Add(wx.StaticText(panel, -1, u'关键字段：'),0,wx.ALIGN_LEFT|wx.ALL, 5)
        self.keywordsField =wx.TextCtrl(panel, -1, u'使用空格分隔多个关键字', size = (200, -1))
        box.Add(self.keywordsField, 1, wx.EXPAND|wx.ALIGN_CENTER|wx.ALL, 5)
        self.matchmodeList = wx.Choice(panel, -1,choices=(u'任意一个',u'匹配全部'))
        self.matchmodeList.SetSelection(0)
        box.Add(self.matchmodeList,0, wx.ALIGN_CENTER|wx.ALL, 5)
        
        sizer.Add(box, 0, wx.GROW|wx.ALIGN_CENTER_VERTICAL|wx.ALL, 5)
        #
        box = wx.GridSizer(rows=2, cols=2, hgap=10, vgap=10)
        self.matchcontentCheck =wx.CheckBox(panel, -1, u'匹配帖子内容')
        box.Add(self.matchcontentCheck, wx.ALIGN_LEFT|wx.ALL, 5)
        self.ignorecaseCheck = wx.CheckBox(panel, -1, u'忽略大小写')
        box.Add(self.ignorecaseCheck, wx.ALIGN_LEFT|wx.ALL, 5)
        sizer.Add(box, 0, wx.GROW|wx.ALL, 10)
        panel.SetSizer(sizer)
        groupsizer.Add(panel, 1, wx.EXPAND, 0)
        groupsizer.Layout()
        parentsizer.Add(groupsizer, 0, wx.EXPAND|wx.ALL, 5)
        return panel
    
    def CreateButton(self, btnsizer, id, label):
        button = wx.Button(self, id, label)
        if id == wx.ID_OK:
            button.SetDefault()
            self.Bind(wx.EVT_BUTTON, self.OnOK, button)
        btnsizer.AddButton(button)

    def InitContent(self):
        if not self.config:
            return
        self.nameField.Clear()
        self.nameField.WriteText(self.config.name)
        adptr = self.config.adapter
        if adptr:
            for i, a in enumerate(self.adapters):
                if adptr.__class__ == a.__class__:
                    self.adapterList.SetSelection(i)
            self.boardName.Clear()
            self.boardName.WriteText(adptr.boardname)
        arg = self.config.watchargs
        if arg:
            # watch mode config
            index = 0
            if arg.themeMode:
                if arg.newPostMode:
                    index = 0
                else:
                    index = 2
            else:
                if arg.newPostMode:
                    index = 1
                else:
                    index = 3
            self.matchModeRadios[index].SetValue(True)
            # match args cofig
            self.keywordsField.Clear()
            self.keywordsField.WriteText(u' '.join(arg.keywords))
            self.matchcontentCheck.SetValue(arg.contentMatch)
            self.ignorecaseCheck.SetValue(arg.ignoreCase)
            if model.WatchArgs.MATCH_TYPE_AND == arg.matchType:
                self.matchmodeList.SetSelection(model.WatchArgs.MATCH_TYPE_AND)
            else:
                self.matchmodeList.SetSelection(model.WatchArgs.MATCH_TYPE_OR)
    
    def GetAdapters(self):
        import pkgutil
        adapters = []
        try:
            modulenames = [name for _, name, _ in pkgutil.iter_modules(adapter.__path__)]
            for modulename in modulenames:
                try:
                    m = __import__('adapter.%s' %(modulename,))
                    module = m.__getattribute__(modulename)
                    clazz =  module.__getattribute__('ConcreteAdapter')
                    adapters.append(clazz())
                except:
                    pass
        except:
            pass
        return adapters
            
            
    def GetWatchConfig(self):
        # adapter
        adapter = self.adapters[self.adapterList.GetSelection()].getCopy()
        adapter.setBoardName(self.boardName.GetValue().strip())
        # watch mode
        args = model.WatchArgs()
        #(u'所有新主题贴',u'所有新帖',u'符合条件的新主题贴',u'符合条件的新帖')
        values = ((True, True),(True, False),(False, True),(False, False))
        for i,radio in enumerate(self.matchModeRadios):
            if radio.GetValue():
                args.newPostMode = values[i][0]
                args.themeMode = values[i][1]
                break
        # match args
        args.enableContentMatch(self.matchcontentCheck.IsChecked())
        args.setIgnoreCase(self.ignorecaseCheck.IsChecked())
        args.setKeywords(self.keywordsField.GetValue().strip().split(' '))
        args.setMatchType(self.matchmodeList.GetSelection())
        return model.WatchConfig(self.nameField.GetValue().strip(), adapter, args)

    def OnOK(self, event):
        v,m = self.ValidateContent()
        if v:
            self.EndModal(wx.ID_OK)
        else:
            wx.MessageBox( u'无法完成编辑，请确认您输入的参数都是有效的。\n无效信息：%s'%(m,),u'无法完成编辑',wx.YES|wx.NO)
    
    def OnMatchModeChanged(self, event): 
        self.updateControlState()
        
    def ValidateContent(self):
        if not len(self.nameField.GetValue().strip()):
            return False,u'没有输入配置名称'
        if not len(self.boardName.GetValue().strip()):
            return False,u'没有输入版面名称'
        if not len(self.keywordsField.GetValue().strip()):
            return False,u'没有输入匹配关键字'

        return True,None

    def updateControlState(self):
        #(u'所有新主题贴',u'所有新帖',u'符合条件的新主题贴',u'符合条件的新帖')
        for i, radiobutton in enumerate(self.matchModeRadios):
            if radiobutton.GetValue():
                if i in (0,1):
                    self.enableArgConfigArea(False)
                else:
                    self.enableArgConfigArea(True)
    
    def enableArgConfigArea(self, enable):
        if enable:
            self.matchArgsConfigArea.Enable()
        else:
            self.matchArgsConfigArea.Disable()
            
if __name__ == '__main__':
    app = wx.PySimpleApp()
    dlg = WatchConfigDialog(None, -1, 'Hello')
    dlg.Show()
    app.MainLoop()